package com.ruoyi.jihuo.service.handler;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.jihuo.domain.JhTmAccount;
import com.ruoyi.jihuo.domain.JhTmGoods;
import com.ruoyi.jihuo.domain.JhTmProductsOnSale;
import com.ruoyi.jihuo.domain.JhTmTemplate;
import com.ruoyi.jihuo.service.IJhTmProductsOnSaleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;

/**
 * @Author：LXY
 * @DATE：2025-09-13 20:56
 * @Description：商品过滤处理器 - 负责根据模板第二页 商品过滤
 */
@Slf4j
@Component
public class Jh10ProductFilterHandler implements PriorityHandler {
    @Autowired
    private IJhTmProductsOnSaleService jhTmProductsOnSaleService;
    @Override
    public int getPriority() {
        return 10;
    }

    @Override
    public boolean handle(ProcessContext<JSONObject> request) throws IOException {
        // 参数校验
        if (Objects.isNull(request) || Objects.isNull(request.getData())) {
            throw new IllegalArgumentException("请求数据不能为空");
        }
        
        JSONObject data = request.getData();
        JhTmGoods item = data.getObject("item", JhTmGoods.class);
        JhTmTemplate template = data.getObject("template", JhTmTemplate.class);
        JhTmAccount tmAccount = data.getObject("tmAccount", JhTmAccount.class);
        JhTmProductsOnSale productsOnSale = data.getObject("productsOnSale", JhTmProductsOnSale.class);
        String jhCategoryId = item.getJhCategoryId();
        data.put("categoryId", jhCategoryId);
        // 基础数据校验
        try {
            validateBasicData(item, template, tmAccount, productsOnSale);
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
        //是否重复上架 (只判断系统内在售商品)
        if (checkReSelling(tmAccount, productsOnSale)) return false;
        // 检查店铺流量是否满足要求
        if (checkShopTraffic(tmAccount, productsOnSale)) return false;
        // 检查品牌是否满足过滤条件
        if (checkBrandFilter(item, template, productsOnSale)) return false;
        // 检查店铺是否满足过滤条件
        if (checkShopFilter(template, item, productsOnSale)) return false;
        // 检查标题关键词是否满足过滤条件
        if (checkTitleKeyword(template, item, productsOnSale)) return false;
        // 检查价格是否在允许范围内
        if (checkPriceRange(template, item, productsOnSale)) return false;
        // 检查总库存是否满足要求
        if (checkTotalInventory(template, item, productsOnSale)) return false;
        // 过滤商品的SKU信息
        filterSkus(template, item, productsOnSale);
        // 检查销量是否满足要求
        if (checkSalesVolume(template, item, productsOnSale)) return false;
        // 检查描述图片是否满足要求
        if (checkDescriptionPictures(template, item, productsOnSale)) return false;
        // 检查英文内容是否符合要求
        if (checkEnglishCharacters(template, item, productsOnSale)) return false;
        return true;
    }

    private boolean checkReSelling(JhTmAccount tmAccount, JhTmProductsOnSale productsOnSale) {
        if (StringUtils.isNotBlank(tmAccount.getJhRepeatSet())){
            if ("0".equals(tmAccount.getJhRepeatSet())){
                boolean exist = jhTmProductsOnSaleService.isExistByJhTmAccountIdAndJhOriginalUrl(tmAccount.getJhId(), productsOnSale.getJhOriginalUrl());
                if (exist){
                    productsOnSale.setJhStatus("1");
                    productsOnSale.setJhExplain("已复制的商品不再复制");
                    return true;
                }
            }
        }
        return false;
    }

    private static boolean checkBrandFilter(JhTmGoods item, JhTmTemplate template, JhTmProductsOnSale productsOnSale) {
        if (StringUtils.isNotBlank(item.getJhBrand()) && CollectionUtils.containsInstance(template.getJhKeywordBrand(), item.getJhBrand())) {
            productsOnSale.setJhStatus("1");
            productsOnSale.setJhExplain(item.getJhBrand() + "-品牌是需要被过滤掉的品牌");
            return true;
        }
        return false;
    }

    private static boolean checkShopTraffic(JhTmAccount tmAccount, JhTmProductsOnSale productsOnSale) {
        if (tmAccount.getJhTrafficNum() <= 0) {
            productsOnSale.setJhStatus("1");
            productsOnSale.setJhExplain(tmAccount.getJhName() + "-店铺流量不足");
            return true;
        }
        return false;
    }

    /**
     * 校验基础数据是否完整
     */
    private void validateBasicData(JhTmGoods item, JhTmTemplate template, 
                                 JhTmAccount account, JhTmProductsOnSale products) {
        if (Objects.isNull(item)) {
            throw new IllegalArgumentException("商品数据不能为空");
        }
        if (Objects.isNull(template)) {
            throw new IllegalArgumentException("模板数据不能为空");
        }
        if (Objects.isNull(account)) {
            throw new IllegalArgumentException("店铺账号数据不能为空");
        }
        if (Objects.isNull(products)) {
            throw new IllegalArgumentException("上架商品数据不能为空");
        }
    }


    
    /**
     * 检查店铺名称是否需要过滤
     */
    private boolean checkShopFilter(JhTmTemplate template, JhTmGoods item, JhTmProductsOnSale products) {
        if (StringUtils.isNotBlank(item.getJhShopName()) && 
            CollectionUtils.containsInstance(template.getJhKeywordShop(), item.getJhShopName())) {
            products.setJhStatus("1");
            products.setJhExplain(item.getJhShopName() + "-店铺名称是需要被过滤掉的店铺名称");
            return true;
        }
        return false;
    }
    
    /**
     * 检查标题是否包含过滤关键字
     */
    private boolean checkTitleKeyword(JhTmTemplate template, JhTmGoods item, JhTmProductsOnSale products) {
        List<String> keywords = template.getJhKeywordTitle();
        String title = item.getJhTitle();
        for (String keyword : keywords) {
            if (containsKeyword(title, keyword)) {
                products.setJhStatus("1");
                products.setJhExplain(keyword + "-标题包含过滤关键字");
                return true;
            }
        }
        return false;
    }
    
    /**
     * 检查价格是否在设定区间内
     */
    private boolean checkPriceRange(JhTmTemplate template, JhTmGoods item, JhTmProductsOnSale products) {
        Long minPrice = template.getJhPriceBegin();
        Long maxPrice = template.getJhPriceEnd();
        Long actualPrice = item.getJhDisprice();
        
        if (Objects.nonNull(actualPrice)) {
            if (Objects.nonNull(minPrice) && actualPrice < minPrice) {
                products.setJhStatus("1");
                products.setJhExplain(actualPrice + "-价格低于最低区间");
                return true;
            }
            if (Objects.nonNull(maxPrice) && actualPrice > maxPrice) {
                products.setJhStatus("1");
                products.setJhExplain(actualPrice + "-价格高于最高区间");
                return true;
            }
        }
        return false;
    }
    
    /**
     * 检查总库存是否符合要求
     */
    private boolean checkTotalInventory(JhTmTemplate template, JhTmGoods item, JhTmProductsOnSale products) {
        Long minInventory = template.getJhTotalInventoryNum();
        if (Objects.nonNull(minInventory) && item.getJhQuantity() < minInventory) {
            products.setJhStatus("1");
            products.setJhExplain(minInventory + "-总库存少于设定的最低总库存数量");
            return true;
        }
        return false;
    }
    
    /**
     * 过滤不符合要求的SKU
     */
    private void filterSkus(JhTmTemplate template, JhTmGoods item, JhTmProductsOnSale products) {
        Long minSkuPrice = template.getJhSkuPriceLess();
        Long maxSkuPrice = template.getJhSkuPriceGreater();
        Long minSkuInventory = template.getJhSkuInventoryLess();
        
        // 如果没有SKU相关过滤条件，直接返回
        if (Objects.isNull(minSkuPrice) && Objects.isNull(maxSkuPrice) && Objects.isNull(minSkuInventory)) {
            return;
        }
        
        JSONArray skus = item.getJhSkus();
        if (Objects.isNull(skus) || skus.isEmpty()) {
            return;
        }
        
        JSONArray newSkus = new JSONArray();

        for (Object skuObj : skus) {
            @SuppressWarnings("unchecked")
            Map<String, Object> sku = (HashMap<String, Object>) skuObj;
            boolean isValidSku = true;
            
            // 检查SKU库存
            if (Objects.nonNull(minSkuInventory)) {
                Integer skuQuantity = (Integer) sku.get("skuQuantity");
                if (Objects.nonNull(skuQuantity) && skuQuantity < minSkuInventory) {
                    log.info("SKU过滤: {} - 库存少于设定的最低SKU库存数量", sku);
                    isValidSku = false;
                }
            }
            
            // 检查SKU价格
            if (isValidSku) {
                Double skuPrice = null;
                try {
                    skuPrice = Double.valueOf((String) sku.get("skuDisPrice"));
                } catch (Exception e) {
                    log.warn("解析SKU价格失败: {}", sku);
                }
                
                if (Objects.nonNull(skuPrice)) {
                    if (Objects.nonNull(minSkuPrice) && skuPrice < minSkuPrice) {
                        log.info("SKU过滤: {} - 价格低于设定的最低SKU价格", sku);
                        isValidSku = false;
                    }
                    if (Objects.nonNull(maxSkuPrice) && skuPrice > maxSkuPrice) {
                        log.info("SKU过滤: {} - 价格高于设定的最高SKU价格", sku);
                        isValidSku = false;
                    }
                }
            }
            
            if (isValidSku) {
                newSkus.add(sku);
            }
        }
        
        item.setJhSkus(newSkus);
    }
    
    /**
     * 检查销量是否符合要求
     */
    private boolean checkSalesVolume(JhTmTemplate template, JhTmGoods item, JhTmProductsOnSale products) {
        Long minSales = template.getJhSalesNum();
        if (Objects.nonNull(minSales) && item.getJhSell() < minSales) {
            products.setJhStatus("1");
            products.setJhExplain(item.getJhSell() + "-销量少于设定的最低销量");
            return true;
        }
        return false;
    }
    
    /**
     * 检查详情图数量是否符合要求
     */
    private boolean checkDescriptionPictures(JhTmTemplate template, JhTmGoods item, JhTmProductsOnSale products) {
        Long minPicNum = template.getJhPictureNum();
        if (Objects.nonNull(minPicNum)) {
            int actualPicCount = countPicture(item.getJhDesc());
            if (actualPicCount < minPicNum) {
                products.setJhStatus("1");
                products.setJhExplain(minPicNum + "-详情图数量低于设定的最低详情图数量");
                return true;
            }
        }
        return false;
    }
    
    /**
     * 检查标题中的英文字符数量是否符合要求
     */
    private boolean checkEnglishCharacters(JhTmTemplate template, JhTmGoods item, JhTmProductsOnSale products) {
        Long maxLetterNum = template.getJhLetterNum();
        if (Objects.nonNull(maxLetterNum)) {
            int actualLetterCount = countEnglishCharacters(item.getJhTitle());
            if (actualLetterCount > maxLetterNum) {
                products.setJhStatus("1");
                products.setJhExplain(item.getJhTitle() + "-标题包含的英文数量大于设定的标题包含英文数量");
                return true;
            }
        }
        return false;
    }
    
    /**
     * 处理过滤结果，设置状态并抛出异常
     */
    private boolean handleFilterResult(JhTmProductsOnSale products, String reason) {
        products.setJhStatus("1");
        products.setJhExplain(reason);
        return false;
    }
    
    /**
     * 计算详情中的图片数量
     */
    private int countPicture(String desc) {
        return StringUtils.isEmpty(desc) ? 0 : StringUtils.countMatches(desc, "<img");
    }
    
    /**
     * 检测文本是否包含指定关键字
     *
     * @param textToCheck 要检查的文本
     * @param keyword     关键字
     * @return 如果包含关键字返回 true，否则返回 false
     */
    private boolean containsKeyword(String textToCheck, String keyword) {
        if (StringUtils.isBlank(textToCheck) || StringUtils.isBlank(keyword)) {
            return false;
        }
        return textToCheck.contains(keyword);
    }
    
    /**
     * 计算字符串中的英文字符数量
     *
     * @param text 要计算的字符串
     * @return 英文字符的数量
     */
    private int countEnglishCharacters(String text) {
        if (StringUtils.isEmpty(text)) {
            return 0;
        }
        
        int count = 0;
        for (char c : text.toCharArray()) {
            if (Character.isLetter(c)) {
                count++;
            }
        }
        return count;
    }
}
